<template>
  <div class="components-tab">
    <el-row :gutter="24" class="components-row">
      <!-- 左侧：两个饼图 -->
      <el-col :xs="24" :lg="12" class="charts-column">
        <el-row :gutter="24" class="charts-row-inner">
          <el-col :xs="24" :lg="24">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <el-icon><PieChart /></el-icon>
                  <span>组件分类统计</span>
                </div>
              </template>
              
              <div ref="componentChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :lg="24">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <el-icon><PieChart /></el-icon>
                  <span>组件错误比例统计 (Error 级别)</span>
                </div>
              </template>
              
              <div ref="errorChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
      
      <!-- 右侧：组件详细列表 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><List /></el-icon>
              <span>组件详细列表</span>
            </div>
          </template>
          
          <div class="table-filter">
            <el-select v-model="selectedCategory" placeholder="筛选类别" style="width: 200px">
              <el-option
                v-for="category in uniqueCategories"
                :key="category"
                :label="category"
                :value="category"
              />
            </el-select>
          </div>

          <div class="table-container">
            <el-table 
              :data="componentList" 
              style="width: 100%"
              stripe
              height="100%"
            >
              <el-table-column prop="name" label="组件名" width="120" />
              <el-table-column prop="category" label="类别" width="100">
                <template #default="{ row }">
                  <el-tag :type="getCategoryType(row.category)" size="small">
                    {{ row.category }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="count" label="日志数" width="80" />
              <el-table-column label="错误级别" min-width="150">
                <template #default="{ row }">
                  <div class="level-tags">
                    <el-tag 
                      v-for="(count, level) in row.levels" 
                      :key="level"
                      :type="getLevelType(String(level))"
                      size="small"
                      class="level-tag"
                    >
                      {{ level }}: {{ count }}
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button link type="primary" size="small" @click="viewComponentLogs(row)">查看日志</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useAnalysisStore } from '@/stores/analysis'
import * as api from '@/api'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'

const router = useRouter()
const emits = defineEmits(['view-component-logs'])

// Store
const analysisStore = useAnalysisStore()

// 图表引用
const componentChartRef = ref<HTMLElement>()
let componentChart: echarts.ECharts | null = null
const errorChartRef = ref<HTMLElement>()
let errorChart: echarts.ECharts | null = null

// 组件数据
const componentData = ref<any>({})

const selectedCategory = ref('所有类别') // 新增：选中类别，默认为所有类别
const availableCategories = ref<string[]>([]) // 新增：存储从后端获取的顶级分类

// 计算属性
const componentList = computed(() => {
  const filteredComponents = Object.entries(componentData.value).filter(([name, data]: [string, any]) => {
    return selectedCategory.value === '所有类别' || data.category === selectedCategory.value
  })
  
  return filteredComponents.map(([name, data]: [string, any]) => ({
    name,
    category: data.category,
    count: data.count,
    levels: data.levels
  })).sort((a, b) => {
    const errorA = a.levels?.ERROR || 0
    const errorB = b.levels?.ERROR || 0
    return errorB - errorA // 降序排列
  })
})

const errorRatioList = computed(() => {
  const errorCounts: Record<string, number> = {}
  let totalErrorCount = 0
  
  for (const name in componentData.value) {
    const component = componentData.value[name]
    if (component.levels && component.levels.ERROR) {
      errorCounts[name] = component.levels.ERROR
      totalErrorCount += component.levels.ERROR
    }
  }

  return Object.entries(errorCounts).map(([name, count]) => ({
    name,
    value: count,
    percentage: totalErrorCount > 0 ? ((count / totalErrorCount) * 100).toFixed(2) : 0
  }))
})

const uniqueCategories = computed(() => {
  // 使用从后端获取的顶级分类，并添加 '所有类别' 和 'others'
  return ['所有类别', ...availableCategories.value, 'others'].sort()
})

// 获取类别类型
const getCategoryType = (category: string) => {
  const types: Record<string, string> = {
    'bmc_core': 'primary',
    'config': 'success',
    'framework': 'warning',
    'hardware': 'danger',
    'interface': 'info',
    'om': '',
    'opensource': 'success',
    'security': 'danger',
    'others': 'info' // 新增：为未匹配的类别定义类型
  }
  return types[category] || 'info'
}

// 获取日志级别类型
const getLevelType = (level: string) => {
  switch (level.toLowerCase()) {
    case 'error': return 'danger'
    case 'warning': return 'warning'
    case 'info': return 'info'
    default: return 'info'
  }
}

const viewComponentLogs = (component: any) => {
  emits('view-component-logs', { componentName: component.name })
}

// 加载组件数据
const loadComponentData = async () => {
  try {
    const data = await api.getComponents()
    if ((data as any).error) {
      console.error('加载组件数据失败:', (data as any).error)
      return
    }
    componentData.value = data
    console.log('loadComponentData - Raw API data:', data)
  } catch (error) {
    console.error('加载组件数据失败:', error)
  }
}

// 新增：加载组件分类
const loadComponentCategories = async () => {
  try {
    const data = await api.getComponentCategories()
    if (Array.isArray(data)) {
      availableCategories.value = data
    } else if ((data as any).error) {
      console.error('获取组件分类失败:', (data as any).error)
    }
  } catch (error) {
    console.error('获取组件分类失败:', error)
  }
}

// 初始化组件分类图表
const initComponentChart = () => {
  if (!componentChartRef.value) return
  
  componentChart = echarts.init(componentChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '组件分类',
        type: 'pie',
        radius: '50%',
        center: ['50%', '50%'],
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  componentChart.setOption(option)
}

const initErrorChart = () => {
  if (!errorChartRef.value) return

  errorChart = echarts.init(errorChartRef.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '组件错误比例',
        type: 'pie',
        radius: '50%',
        center: ['50%', '50%'],
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  errorChart.setOption(option)
}

// 更新组件分类图表
const updateComponentChart = () => {
  if (!componentChart || !componentData.value) return

  const categories: Record<string, number> = {}

  Object.values(componentData.value).forEach((component: any) => {
    const category = component.category
    categories[category] = (categories[category] || 0) + component.count
  })

  const data = Object.entries(categories).map(([category, count]) => ({
    name: category,
    value: count
  }))

  console.log('updateComponentChart - Chart data:', data)

  componentChart.setOption({
    series: [{
      data
    }]
  })
}

const updateErrorChart = () => {
  if (!errorChart) return

  const chartData = errorRatioList.value.map(item => ({
    name: item.name,
    value: item.value
  }))

  console.log('updateErrorChart - Chart data:', chartData)

  errorChart.setOption({
    series: [{
      data: chartData
    }]
  })
}

// 监听数据变化
watch(componentData, () => {
  updateComponentChart()
  updateErrorChart()
}, { deep: true })

// 组件挂载
onMounted(async () => {
  await loadComponentData()
  await loadComponentCategories()
  
  initComponentChart()
  initErrorChart()
  updateComponentChart() // 首次加载数据后更新图表
  updateErrorChart()     // 首次加载数据后更新图表
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    componentChart?.resize()
    errorChart?.resize()
  })
})
</script>

<style scoped>
.components-tab {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.components-row {
  flex: 1;
  height: 100%;
}

.components-row :deep(.el-col) {
  height: 100%;
}

.charts-column {
  display: flex;
  flex-direction: column;
}

.charts-row-inner {
  flex: 1;
  height: 100%;
}

.charts-row-inner :deep(.el-col) {
  height: 50%;
  display: flex;
  flex-direction: column;
}

.chart-card {
  height: 100%;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  flex-shrink: 0;
}

.chart-card :deep(.el-card__body) {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
}

.table-container {
  flex: 1;
  overflow: hidden;
}

.table-filter {
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.level-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.level-tag {
  font-size: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .components-row {
    flex-direction: column;
  }
  
  .components-row :deep(.el-col) {
    height: auto;
    margin-bottom: 16px;
  }
  
  .chart-card {
    height: 400px;
  }
  
  .chart-container {
    min-height: 250px;
  }
}

@media (max-width: 480px) {
  .components-tab {
    padding: 0;
  }
  
  .chart-container {
    min-height: 200px;
  }
}
</style> 